package cn.itcast.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: HuYi.Zhang
 * @create: 2018-07-14 18:08
 **/
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        // 获取request对象
        HttpServletRequest req = ctx.getRequest();
        // 判断参数中是否有access-token
        String token = req.getParameter("access-token");
        if(StringUtils.isBlank(token)){
            // 未登录，返回错误
            ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            // 阻止访问
            ctx.setSendZuulResponse(false);
        }
        return null;
    }
}
